package com.shijiwei.lifthelper.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.overlayutil.OverlayManager;
import com.baidu.mapapi.overlayutil.PoiOverlay;
import com.baidu.mapapi.overlayutil.WalkingRouteOverlay;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.RouteLine;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRoutePlanOption;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.baidu.mapapi.utils.DistanceUtil;
import com.shijiwei.lifthelper.R;
import com.shijiwei.lifthelper.utils.DistanceUtils;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.math.BigDecimal;

import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * Created by sjw on 2015/12/12.
 */
@ContentView(R.layout.fragment_map)
public class MapFragment extends BaseFragment {
    @ViewInject(R.id.mMapView)
    private MapView mapView;
    @ViewInject(R.id.cb_trafic_map)
    private CheckBox trafic;
    @ViewInject(R.id.cb_mapmode)
    private CheckBox mapMode;
    @ViewInject(R.id.et_search)
    private EditText search;
    @ViewInject(R.id.btn_search)
    private Button btnSearch;

    private PopupWindow popupWindow;

    //地图管理工具类
    private BaiduMap baiduMap;
    //搜索
    private PoiSearch poiSearch;
    //定位
    private LocationClient locationClient;
    private LocationClientOption locationClientOption;
    //定位到当前位置的经纬度坐标点
    private LatLng point;
    private LatLng poiPoint;
    //判断是否第一次进入地图界面
    private boolean isFirst = true;
    //收索关键字
    private String keyword;
    private ImageView share;
    private ImageView go;

    //公交查询RoutePlanSearch
    private RoutePlanSearch route;
    private RouteLine routeLine;
    private OverlayManager routeOverlay;
    private InfoWindow infoWindow;
    private LatLng nodeLocation;
    private String nodeTitle;


    public static MapFragment newInstance() {

        Bundle args = new Bundle();

        MapFragment fragment = new MapFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void initView() {
        addPopupWindow();
        baiduMap = mapView.getMap();
        poiSearch = PoiSearch.newInstance();
        route = RoutePlanSearch.newInstance();
        locationClient = new LocationClient(getActivity());
        locationClientOption = new LocationClientOption();
    }

    @Override
    public void initData() {
        location();
        addListener();
    }

    /**
     * 添加设置地图模式的窗口
     */
    private void addPopupWindow() {
        View view = getActivity().getLayoutInflater().inflate(R.layout.layout_popupwindow, null);
        popupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, false);

        LinearLayout satellite = (LinearLayout) view.findViewById(R.id.mode_satellite);
        LinearLayout mode2d = (LinearLayout) view.findViewById(R.id.mode_2d);
        satellite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                baiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
            }
        });

        mode2d.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                baiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
            }
        });


    }


    /**
     * 添加监听事件
     */
    private void addListener() {
        trafic.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    baiduMap.setTrafficEnabled(true);
                } else {
                    baiduMap.setTrafficEnabled(false);
                }
            }
        });

        mapMode.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    popupWindow.showAsDropDown(mapMode);
                } else {
                    popupWindow.dismiss();
                }
            }
        });

        /**
         * 搜索事件
         */
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                keyword = search.getText().toString();
                if (TextUtils.isEmpty(keyword)) {
                    Toast.makeText(getActivity(), "搜索内容不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    poiSearch.searchNearby(new PoiNearbySearchOption()
                            .location(point)
                            .keyword(keyword)
                            .radius(5000));
                }

            }
        });

        //获得搜索结果的回调
        poiSearch.setOnGetPoiSearchResultListener(new OnGetPoiSearchResultListener() {
            @Override
            public void onGetPoiResult(PoiResult poiResult) {
                if (poiResult == null || poiResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
                    Toast.makeText(getActivity(), "没有搜索到结果", Toast.LENGTH_SHORT).show();
                    return;
                } else if (poiResult.error == SearchResult.ERRORNO.NO_ERROR) {
                    baiduMap.clear();//清除之前已有的所有覆盖物
                    //创建PoiOverlay
                    PoiOverlay overlay = new MyPoiOverlay(baiduMap);
                    //设置overlay可以处理标注点击事件
                    baiduMap.setOnMarkerClickListener(overlay);
                    //设置PoiOverlay数据
                    overlay.setData(poiResult);
                    //添加PoiOverlay到地图中
                    overlay.addToMap();
                    overlay.zoomToSpan();
                }
            }

            @Override
            public void onGetPoiDetailResult(final PoiDetailResult poiDetailResult) {
                View v = LayoutInflater.from(getActivity())
                        .inflate(R.layout.poi_item, null);
                share = (ImageView) v.findViewById(R.id.iv_share);
                go = (ImageView) v.findViewById(R.id.iv_go);
                ((TextView) v.findViewById(R.id.tv_adress))
                        .setText("地址："
                                + (poiDetailResult.getAddress().equals(null) ? "暂无"
                                : poiDetailResult.getAddress()));
                ((TextView) v.findViewById(R.id.tv_name)).setText("名称："
                        + (poiDetailResult.getName().equals(null) ? "暂无" : poiDetailResult
                        .getName()));
                ((TextView) v.findViewById(R.id.tv_phone))
                        .setText("电话："
                                + (poiDetailResult.getTelephone().equals("") ? "暂无"
                                : poiDetailResult.getTelephone()));
                ((TextView) v.findViewById(R.id.tv_price))
                        .setText("价格："
                                + (poiDetailResult.getPrice() == 0 ? "暂无" : (poiDetailResult
                                .getPrice() + " 元")));
                ((TextView) v.findViewById(R.id.tv_shopHours))
                        .setText("营业时间："
                                + (poiDetailResult.getShopHours().equals("") ? "暂无"
                                : poiDetailResult.getShopHours()));
                double distance = DistanceUtil.getDistance(point, poiDetailResult.getLocation());
                ((TextView) v.findViewById(R.id.tv_distance)).setText(DistanceUtils.format(distance, 2, BigDecimal.ROUND_UP));
                infoWindow = new InfoWindow(v, poiDetailResult
                        .getLocation(), -50);
                baiduMap.showInfoWindow(infoWindow);
                share.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        OnekeyShare oks = new OnekeyShare();
                        oks.setDialogMode();
                        oks.disableSSOWhenAuthorize();
                        oks.setText(poiDetailResult.getName() + ":" + poiDetailResult.getAddress());
                        oks.show(getActivity());
                    }
                });
                go.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {//去目的地
                        PlanNode stNode = PlanNode.withLocation(point);
                        PlanNode endNode = PlanNode.withLocation(poiDetailResult.getLocation());
                        route.walkingSearch(new WalkingRoutePlanOption().from(stNode).to(endNode));
                        poiPoint = poiDetailResult.getLocation();
                    }
                });
            }
        });
        //线路规划，接口回调
        route.setOnGetRoutePlanResultListener(new OnGetRoutePlanResultListener() {
            @Override
            public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

                routeLine = (RouteLine) walkingRouteResult.getRouteLines().get(0);
                WalkingRouteOverlay overlay = new WalkingRouteOverlay(baiduMap);
                if (routeOverlay != null) {
                    routeOverlay.removeFromMap();
                }
                routeOverlay = overlay;
                overlay.setData(walkingRouteResult.getRouteLines().get(0));
                overlay.addToMap();
                overlay.zoomToSpan();

//                Object step = routeLine.getAllStep().get(0);
//                nodeLocation = ((WalkingRouteLine.WalkingStep) step).getEntrance().getLocation();
//                nodeTitle = ((WalkingRouteLine.WalkingStep) step).getInstructions();
//                if (nodeLocation == null || nodeTitle == null) {
//                    return;
//                }
//                // 移动节点至中心
//                baiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(nodeLocation));
//                // show popup
//                TextView popupText = new TextView(getActivity());
////                popupText.setBackgroundResource(R.drawable.popup);
//                popupText.setTextColor(0xFF000000);
//                popupText.setText(nodeTitle);
//                baiduMap.showInfoWindow(new InfoWindow(popupText, nodeLocation, 0));



            }

            @Override
            public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

            }

            @Override
            public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {

            }
        });


        /**
         * 地图点击事件、
         */
        baiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                baiduMap.hideInfoWindow();
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
                mapMode.setChecked(false);
            }

            @Override
            public boolean onMapPoiClick(final MapPoi mapPoi) {
                ImageView imageView = new ImageView(getActivity());
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT);
                imageView.setLayoutParams(params);
                imageView.setImageResource(R.mipmap.goto_destination);
                InfoWindow window = new InfoWindow(imageView, mapPoi.getPosition(), -50);
                baiduMap.showInfoWindow(window);
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PlanNode stNode = PlanNode.withLocation(point);
                        PlanNode endNode = PlanNode.withLocation(mapPoi.getPosition());
                        route.walkingSearch(new WalkingRoutePlanOption().from(stNode).to(endNode));
                    }
                });
                poiPoint = mapPoi.getPosition();
                return false;
            }


        });


    }

    /**
     * 定位
     */
    public void location() {
        baiduMap.setMyLocationEnabled(true);
        locationClientOption.setOpenGps(true);
        locationClientOption.setCoorType("bd09ll");
        locationClientOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        locationClientOption.setScanSpan(2000);
        locationClientOption.setIsNeedLocationPoiList(true);
        locationClientOption.setIsNeedAddress(true);
        locationClient.setLocOption(locationClientOption);
        locationClient.start();
        locationClient.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                point = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());

                baiduMap.setMyLocationData(new MyLocationData.Builder()
                        .latitude(bdLocation.getLatitude())
                        .longitude(bdLocation.getLongitude())
                        .build());
                //第一次进入地图，将地图的中心位置设置成当前位置
                if (isFirst) {
                    MapStatus mapStatus = new MapStatus.Builder().target(point).zoom(17).build();
                    baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(mapStatus));
                    isFirst = false;
                }
            }
        });


    }


    @Override
    public void onStart() {
        super.onStart();
        isFirst = true;
        locationClient.start();
    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
        locationClient.stop();

    }

    @Override
    public void onStop() {
        super.onStop();
        locationClient.stop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        locationClient.stop();
        poiSearch.destroy();
    }


    class MyPoiOverlay extends PoiOverlay {

        /**
         * 构造函数
         *
         * @param baiduMap 该 PoiOverlay 引用的 BaiduMap 对象
         */
        public MyPoiOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public boolean onPoiClick(int i) {
            PoiInfo info = this.getPoiResult().getAllPoi().get(i);
            poiSearch.searchPoiDetail(new PoiDetailSearchOption()
                    .poiUid(info.uid));
            return super.onPoiClick(i);
        }


    }

}
